import sys
import uuid
import requests
from PySide2.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget, 
                              QLabel, QLineEdit, QPushButton, QMessageBox, QDialog)
from PySide2.QtCore import Qt, QSettings, QTimer
from datetime import datetime

class LicenseDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("软件激活")
        self.setFixedSize(400, 250)
        self.setWindowModality(Qt.ApplicationModal)
        
        self.machine_id = self.get_machine_id()
        self.init_ui()
    
    def get_machine_id(self):
        import platform
        import hashlib
        
        # 收集多种机器特征生成唯一ID
        info = {
            'node': platform.node(),
            'mac': hex(uuid.getnode()),
            'processor': platform.processor(),
            'machine': platform.machine()
        }
        return hashlib.sha256(str(info).encode('utf-8')).hexdigest()
    
    def init_ui(self):
        layout = QVBoxLayout()
        
        self.title_label = QLabel("请输入您的激活码")
        self.title_label.setStyleSheet("font-size: 18px; font-weight: bold;")
        layout.addWidget(self.title_label)
        
        layout.addSpacing(20)
        
        self.license_input = QLineEdit()
        self.license_input.setPlaceholderText("请输入16位激活码")
        layout.addWidget(self.license_input)
        
        self.activate_btn = QPushButton("激活")
        self.activate_btn.clicked.connect(self.activate_license)
        layout.addWidget(self.activate_btn)
        
        self.status_label = QLabel("状态: 未激活")
        layout.addWidget(self.status_label)
        
        self.info_label = QLabel(f"机器指纹: {self.machine_id[:8]}...")  # 只显示部分指纹
        self.info_label.setStyleSheet("font-size: 10px; color: gray;")
        layout.addWidget(self.info_label)
        
        self.setLayout(layout)
    
    def activate_license(self):
        license_key = self.license_input.text().strip()
        
        if not license_key or len(license_key) != 16:
            QMessageBox.warning(self, "错误", "请输入有效的16位激活码")
            return
        
        server_url = "http://127.0.0.1:5000/api/check_license"
        
        try:
            response = requests.post(server_url, json={
                'license_key': license_key,
                'machine_id': self.machine_id
            })
            
            result = response.json()
            
            if result.get('valid'):
                # 保存激活信息
                settings = QSettings("MyCompany", "MyApp")
                settings.setValue("license_key", license_key)
                settings.setValue("machine_id", self.machine_id)
                settings.setValue("expires_at", result.get('expires_at', ''))
                settings.setValue("signature", result.get('signature', ''))
                
                self.accept()  # 关闭对话框
            else:
                QMessageBox.critical(self, "错误", result.get('message', '激活失败'))
                
        except requests.exceptions.RequestException as e:
            QMessageBox.critical(self, "错误", f"无法连接服务器: {str(e)}")

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("主界面")
        self.setFixedSize(600, 400)
        
        self.init_ui()
        self.setup_timer()
    
    def init_ui(self):
        central_widget = QWidget()
        layout = QVBoxLayout()
        
        self.title_label = QLabel("Hello, 欢迎使用本软件!")
        self.title_label.setStyleSheet("font-size: 24px; font-weight: bold;")
        self.title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.title_label)
        
        self.status_label = QLabel()
        self.status_label.setStyleSheet("font-size: 14px;")
        self.status_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.status_label)
        
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)
    
    def setup_timer(self):
        # 每小时验证一次许可证
        self.timer = QTimer()
        self.timer.timeout.connect(self.check_license_status)
        self.timer.start(3600000)
        
        # 立即检查一次
        self.check_license_status()
    
    def check_license_status(self):
        settings = QSettings("MyCompany", "MyApp")
        license_key = settings.value("license_key", "")
        machine_id = settings.value("machine_id", "")
        expires_at = settings.value("expires_at", "")
        signature = settings.value("signature", "")
        
        if not all([license_key, machine_id, expires_at, signature]):
            self.close()
            return
        
        # 更新界面显示
        self.status_label.setText(f"软件已激活，有效期至: {expires_at[:10]}")
        
        # 验证签名和有效期
        server_url = "http://127.0.0.1:5000/api/validate_license"
        try:
            response = requests.post(server_url, json={
                'license_key': license_key,
                'machine_id': machine_id,
                'signature': signature
            })
            
            if not response.json().get('valid', False):
                QMessageBox.critical(self, "许可证无效", "许可证验证失败，软件将关闭")
                self.close()
        except requests.exceptions.RequestException:
            # 网络错误时检查本地有效期
            try:
                expires_date = datetime.strptime(expires_at, '%Y-%m-%d %H:%M:%S.%f')
                if datetime.now() > expires_date:
                    QMessageBox.critical(self, "许可证过期", "您的许可证已过期")
                    self.close()
            except:
                self.close()

class AppManager:
    def __init__(self):
        self.app = QApplication(sys.argv)
    
    def validate_license(self):
        settings = QSettings("MyCompany", "MyApp")
        license_key = settings.value("license_key", "")
        machine_id = settings.value("machine_id", "")
        expires_at = settings.value("expires_at", "")
        signature = settings.value("signature", "")
        
        if not all([license_key, machine_id, expires_at, signature]):
            return False
        
        # 验证签名
        server_url = "http://127.0.0.1:5000/api/verify_signature"
        try:
            response = requests.post(server_url, json={
                'license_key': license_key,
                'machine_id': machine_id,
                'expires_at': expires_at,
                'signature': signature
            })
            if not response.json().get('valid', False):
                return False
        except:
            return False
        
        # 检查本地有效期
        try:
            expires_date = datetime.strptime(expires_at, '%Y-%m-%d %H:%M:%S.%f')
            return datetime.now() <= expires_date
        except:
            return False
    
    def run(self):
        if not self.validate_license():
            # 显示激活对话框
            dialog = LicenseDialog()
            if dialog.exec_() != QDialog.Accepted:
                sys.exit()  # 用户取消激活，退出程序
        
        # 显示主界面
        main_window = MainWindow()
        main_window.show()
        sys.exit(self.app.exec_())

if __name__ == '__main__':
    app_manager = AppManager()
    app_manager.run()